package com.mashibing.service.impl.redisImpl;

import com.mashibing.internalcommon.constant.CommonStatusEnum;
import com.mashibing.internalcommon.dto.ResponseResult;
import com.mashibing.internalcommon.request.DriverGrabRequest;
import com.mashibing.service.GrabService;
import com.mashibing.service.OrderService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service("grabRedisDivService")
public class GrabByRedisDiyServiceImpl implements GrabService {

    @Autowired
    private OrderService orderService;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private RenewRedisLockService renewRedisLockService;

    @Override
    public ResponseResult grab(DriverGrabRequest driverGrabRequest) {

        String driverId = driverGrabRequest.getDriverId() + "-" + UUID.randomUUID();
        String orderIdKey = driverGrabRequest.getOrderId() + "";

        System.out.println("开始锁redis diy");

        Boolean aBoolean = stringRedisTemplate.opsForValue().setIfAbsent(orderIdKey, driverId, 20, TimeUnit.SECONDS);

        if (Boolean.TRUE.equals(aBoolean)) {
            renewRedisLockService.renewRedisLock(driverId, orderIdKey, 20);

            // 模拟实际情况测试代码
            try {
                TimeUnit.SECONDS.sleep(10);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }

            orderService.driverGrab(driverGrabRequest);

            // 再次查询value，确定是当前程序的锁
            String value = stringRedisTemplate.opsForValue().get(orderIdKey);
            if (!StringUtils.isBlank(value) && value.equals(driverId)) {
                stringRedisTemplate.delete(orderIdKey);
            }
            System.out.println("结束锁redis diy");

        } else {
            return ResponseResult.fail(CommonStatusEnum.ORDER_GRABING.getCode(), CommonStatusEnum.ORDER_GRABING.getMessage(), null);
        }

        return ResponseResult.success();
    }


}
